<template>
  <div class='container'>
    <el-dialog
      :title="row.id?'编辑学科':'新增学科'"
      :visible.sync="addDialogVisible"
      width="20%"
      :before-close="handleClose">
      <el-form
        ref="form"
        :rules="addFormRules"
        :model="addForm"
        label-width="80px">
        <el-form-item label="学科名称" prop="subjectName">
          <el-input v-model="addForm.subjectName"></el-input>
        </el-form-item>
        <el-form-item label="是否显示">
          <el-switch
          :active-value="1"
          :inactive-value="0"
          inactive-color="#ff4949"
          active-color="#13ce66"
          v-model="addForm.isFrontDisplay">
            <!-- <template slot-scope="{row}">
              {{row.isFrontDisplay===0?'false':'true'}}
          </template> -->
          </el-switch>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="onSave">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { add, update } from '@/api/hmmm/subjects.js'
import { Message } from 'element-ui'

export default {
  name: 'addSubject',
  model: {
    prop: 'addDialogVisible'
  },
  props: {
    addDialogVisible: {
      type: Boolean,
      required: true
    },
    row: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      addForm: {
        subjectName: this.row ? this.row.subjectName : '',
        isFrontDisplay: 0
      },
      addFormRules: {
        subjectName: [
          { required: true, message: '请输入学科名称', trigger: 'blur' },
          { min: 2, max: 7, message: '长度在 2 到 7 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    row: {
      handler (val) {
        this.addForm.subjectName = val === null ? '' : val.subjectName
        this.addForm.isFrontDisplay = val === null ? 0 : val.isFrontDisplay
        // console.log(val)
      }
    }
  },
  created () {

  },

  methods: {
    // 对话框关闭
    handleClose () {
      // 重置表单
      this.$refs.form.resetFields()
      this.$emit('reset')
      this.$emit('input', false)
    },
    // 点击确定提交新增
    async onSave () {
      // 表单验证
      // await this.$refs.form.validate()
      if (this.row.id) {
        // 编辑
        await update({
          ...this.addForm,
          id: this.row.id
        })
        this.$message.success('修改成功')
        this.$emit('edit-success')
      } else {
        // 验证通过添加
        await this.$refs.form.validate()
        await add(this.addForm)
        Message.success('添加成功')
        this.$emit('add-success')
      }
      this.handleClose()
    }
  }
}
</script>

<style scoped lang='less'>

</style>
